<template>
  <div class="search">
    <van-nav-bar
      title="搜索中心"
      left-arrow
      @click-left="$router.back()"
    ></van-nav-bar>

    <!-- 搜索框 -->
    <van-search
      v-model="value"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      @input="inputFn"
      @search="onSearch(value)"
    >
      <template #action>
        <div @click="onSearch(value)">搜索</div>
      </template>
    </van-search>

    <!-- 推荐 -->
    <van-cell-group>
      <!-- 给cell设置title，span标签不会识别 -->
      <!-- :title=""highLight(item, value)" -->
      <van-cell
        icon="search"
        v-for="(item, index) in sugList"
        :key="index"
        @click="onSearch(item)"
      >
        <span v-html="highLight(item, value)"></span>
      </van-cell>
    </van-cell-group>

    <!-- 历史记录 -->
    <van-cell-group>
      <van-cell title="历史记录"></van-cell>

      <van-cell
        @click="onSearch(item)"
        :title="item"
        v-for="item in history"
        :key="item"
      >
        <van-icon name="close" @click.stop="del(item)" />
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggest } from '@/api/search'
import {
  setStroageSearchHistory,
  getStroageSearchHistory
} from '@/utils/storage'

export default {
  name: 'Search',
  data() {
    return {
      value: '',
      sugList: [],
      history: getStroageSearchHistory()
    }
  },
  methods: {
    // 高亮
    highLight(str, keyword) {
      const reg = new RegExp(keyword, 'gi')
      return str.replace(
        reg,
        (item) => `<span style="color:red">${item}</span>`
      )
    },
    // 搜索
    inputFn() {
      // 防抖
      clearTimeout(this.timerId)
      this.timerId = setTimeout(async () => {
        if (!this.value) return
        const res = await getSuggest(this.value)
        if (res.data.options[0] === null) {
          // 这次是没有数据的
          return (this.sugList = [])
        }
        this.sugList = res.data.options
      }, 300)
    },
    onSearch(item) {
      // if (!item) return this.$toast('请输入关键字')
      console.log('搜索中... ', item)

      // 操作历史记录有要求
      //  1. 最新的在最前面 unshift
      //  2. 数组里面不能有重复的，先删在添加
      // 先删
      this.history = this.history.filter((v) => v !== item)
      // 在添加
      this.history.unshift(item)

      // 存到本地
      setStroageSearchHistory(this.history)

      // 跳转页面
      this.$router.push({
        path: '/search/result',
        query: {
          // 通过query来携带查询参数
          keyword: item
        }
      })
    },
    del(item) {
      // 删除历史记录
      this.history = this.history.filter((v) => v !== item)
      // 存到本地
      setStroageSearchHistory(this.history)
    }
  }
}
</script>

<style></style>
